package com.bcu.cn.onlineexamsystem.studentmanage.service.impl;

import com.bcu.cn.onlineexamsystem.studentmanage.entity.Question;
import com.bcu.cn.onlineexamsystem.studentmanage.entity.StudentAnswer;
import com.bcu.cn.onlineexamsystem.studentmanage.entity.StudentExam;
import com.bcu.cn.onlineexamsystem.studentmanage.mapper.StudentQuestionMapper;
import com.bcu.cn.onlineexamsystem.studentmanage.mapper.StudentAnswerMapper;
import com.bcu.cn.onlineexamsystem.studentmanage.mapper.StudentExamMapper;
import com.bcu.cn.onlineexamsystem.studentmanage.service.StudentExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.jdbc.core.JdbcTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class StudentExamServiceImpl implements StudentExamService {

    @Autowired
    private StudentExamMapper studentExamMapper;
    
    @Autowired
    private StudentQuestionMapper questionMapper;
    
    @Autowired
    private StudentAnswerMapper studentAnswerMapper;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional
    public StudentExam startExam(String studentId, Long examId) {
        StudentExam existingExam = studentExamMapper.findByStudentAndExam(studentId, examId);
        if (existingExam != null) {
            // 日志输出
            System.out.println("[考试开始] 已有考试记录: " + existingExam);
            // 如果startTime为null，补写一次
            if (existingExam.getStartTime() == null) {
                existingExam.setStartTime(LocalDateTime.now());
                System.out.println("[考试开始] 补写startTime: " + existingExam.getStartTime());
                studentExamMapper.updateStartTime(existingExam);
                // 重新查一次
                return studentExamMapper.findByStudentAndExam(studentId, examId);
            }
            return existingExam;
        }

        // 创建新的考试记录（先插入，后更新start_time）
        StudentExam studentExam = new StudentExam();
        studentExam.setStudentId(studentId);
        studentExam.setExamId(examId);
        studentExam.setStatus(1); // 考试中
        studentExamMapper.insert(studentExam);
        // 再更新start_time
        studentExam.setStartTime(LocalDateTime.now());
        System.out.println("[考试开始] 设置startTime: " + studentExam.getStartTime());
        studentExamMapper.updateStartTime(studentExam);
        // 返回最新对象
        return studentExamMapper.findByStudentAndExam(studentId, examId);
    }

    @Override
    public List<Question> getExamQuestions(Long examId) {
        List<Question> questions = questionMapper.findByExamId(examId);
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
        for (Question q : questions) {
            if ("choice".equals(q.getType()) && q.getOptions() != null) {
                try {
                    java.util.List<String> optionList = objectMapper.readValue(q.getOptions(), new com.fasterxml.jackson.core.type.TypeReference<java.util.List<String>>() {});
                    q.setOptionList(optionList);
                } catch (Exception e) {
                    q.setOptionList(java.util.Collections.emptyList());
                }
            }
        }
        return questions;
    }

    @Override
    @Transactional
    public void saveAnswer(StudentAnswer answer) {
        // 检查是否已存在答案
        StudentAnswer existingAnswer = studentAnswerMapper.findByRecordAndQuestion(
            answer.getRecordId(), answer.getQuestionId());
        
        if (existingAnswer != null) {
            // 更新现有答案
            studentAnswerMapper.updateAnswer(answer);
        } else {
            // 插入新答案
            studentAnswerMapper.insert(answer);
        }
    }

    @Override
    @Transactional
    public void submitExam(Long recordId, List<StudentAnswer> answers) {
        // 保存所有答案
        for (StudentAnswer answer : answers) {
            saveAnswer(answer);
        }

        // 更新考试状态
        StudentExam studentExam = new StudentExam();
        studentExam.setRecordId(recordId);
        studentExam.setSubmitTime(LocalDateTime.now());
        System.out.println("[考试提交] 设置submitTime: " + studentExam.getSubmitTime());
        studentExam.setStatus(2); // 已提交
        
        studentExamMapper.updateSubmitStatus(studentExam);
    }

    @Override
    public StudentExam getExamStatus(String studentId, Long examId) {
        return studentExamMapper.findByStudentAndExam(studentId, examId);
    }
    
    @Override
    public Integer getExamDuration(Long examId) {
        String sql = "SELECT duration FROM exams WHERE exam_id = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, examId);
    }

    @Override
    public List<StudentAnswer> getSavedAnswers(Long recordId) {
        return studentAnswerMapper.findByRecordId(recordId);
    }

    @Override
    public Map<String, Object> getExamDetailForStudent(Long examId) {
        Map<String, Object> detail = new java.util.HashMap<>();
        // 查询考试基本信息
        String examSql = "SELECT e.*, c.course_name, u.real_name as teacher_name FROM exams e LEFT JOIN courses c ON e.course_id = c.course_id LEFT JOIN users u ON e.teacher_id = u.user_id WHERE e.exam_id = ?";
        Map<String, Object> exam = jdbcTemplate.queryForMap(examSql, examId);
        detail.put("examName", exam.get("exam_name"));
        detail.put("courseName", exam.get("course_name"));
        detail.put("examType", exam.get("exam_type"));
        detail.put("teacherName", exam.get("teacher_name"));
        detail.put("startTime", exam.get("start_time"));
        detail.put("endTime", exam.get("end_time"));
        detail.put("duration", exam.get("duration"));
        detail.put("totalScore", exam.get("total_score"));
        detail.put("status", exam.get("status"));
        // 查询班级
        String classSql = "SELECT c.class_name FROM exam_classes ec LEFT JOIN classes c ON ec.class_id = c.class_id WHERE ec.exam_id = ? LIMIT 1";
        try {
            String className = jdbcTemplate.queryForObject(classSql, String.class, examId);
            detail.put("className", className);
        } catch (Exception e) {
            detail.put("className", "-");
        }
        // 查询题目列表
        String qSql = "SELECT q.type, q.content, q.score, q.answer FROM exam_questions eq LEFT JOIN questions q ON eq.question_id = q.question_id WHERE eq.exam_id = ? ORDER BY eq.order_num";
        java.util.List<Map<String, Object>> questions = jdbcTemplate.queryForList(qSql, examId);
        detail.put("questions", questions);
        return detail;
    }

    @Override
    public Long getStudentExamRecordId(String studentId, Long examId) {
        String sql = "SELECT record_id FROM student_exams WHERE student_id = ? AND exam_id = ? LIMIT 1";
        try {
            return jdbcTemplate.queryForObject(sql, Long.class, studentId, examId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Map<String, Object> getExamDetailForStudentWithAnswer(Long examId, Long recordId) {
        Map<String, Object> detail = getExamDetailForStudent(examId);
        if (recordId != null) {
            // 查询学生作答及得分
            String aSql = "SELECT q.type, q.content, q.score, q.answer as stdAnswer, sa.answer as studentAnswer, sa.score as studentScore, sa.teacher_comment FROM exam_questions eq LEFT JOIN questions q ON eq.question_id = q.question_id LEFT JOIN student_answers sa ON sa.question_id = q.question_id AND sa.record_id = ? WHERE eq.exam_id = ? ORDER BY eq.order_num";
            java.util.List<Map<String, Object>> questions = jdbcTemplate.queryForList(aSql, recordId, examId);
            detail.put("questions", questions);
        }
        return detail;
    }
} 